package com.nd.qa.shareplate.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.nd.qa.shareplate.common.CPResultCode;
import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.device.CommonUtils;
import com.nd.qa.shareplate.model.ApkInfo;
import com.nd.qa.shareplate.model.Module;
import com.nd.qa.shareplate.model.PageElement;
import com.nd.qa.shareplate.model.Project;
import com.nd.qa.shareplate.model.ProjectTaskTemp;
import com.nd.qa.shareplate.model.ProjectType;
import com.nd.qa.shareplate.model.ProjectUser;
import com.nd.qa.shareplate.model.ShareDevice;
import com.nd.qa.shareplate.model.ShareMessage;
import com.nd.qa.shareplate.model.SharePage;
import com.nd.qa.shareplate.model.SharePlatFormType;
import com.nd.qa.shareplate.model.ShareScript;
import com.nd.qa.shareplate.model.ShareServer;
import com.nd.qa.shareplate.model.ShareSysLog;
import com.nd.qa.shareplate.model.ShareTestApk;
import com.nd.qa.shareplate.model.TestCases;
import com.nd.qa.shareplate.model.TestClass;
import com.nd.qa.shareplate.script.appium.AppiumScriptTool;
import com.nd.qa.shareplate.script.macaca.MacacaScriptTool;
import com.nd.qa.shareplate.script.realmonkey.RealMonkeyScriptTool;
import com.nd.qa.shareplate.script.robotium.CreateRobotiumTestDemo;
import com.nd.qa.shareplate.script.robotium.GenerateTestApk;
import com.nd.qa.shareplate.script.robotium.RobotiumScriptTool;
import com.nd.qa.shareplate.script.selenium.SeleniumScriptTool;
import com.nd.qa.shareplate.service.ApkService;
import com.nd.qa.shareplate.service.LoginService;
import com.nd.qa.shareplate.service.ModuleService;
import com.nd.qa.shareplate.service.ProjectTaskService;
import com.nd.qa.shareplate.service.ProjectTypeService;
import com.nd.qa.shareplate.service.ProjectUserService;
import com.nd.qa.shareplate.service.ShareDeviceService;
import com.nd.qa.shareplate.service.ShareMessageService;
import com.nd.qa.shareplate.service.ShareScriptService;
import com.nd.qa.shareplate.service.ShareServerService;
import com.nd.qa.shareplate.service.ShareSysLogService;
import com.nd.qa.shareplate.service.TestApkService;
import com.nd.qa.shareplate.service.TestCasesService;
import com.nd.qa.shareplate.service.TestClassService;
import com.nd.qa.shareplate.service.TestStepService;
import com.nd.qa.shareplate.service.PageElementService;
import com.nd.qa.shareplate.service.PageService;
import com.nd.qa.shareplate.service.PlatFormTypeService;
import com.nd.qa.shareplate.service.ProjectService;
import com.nd.qa.shareplate.util.CSTools;
import com.nd.qa.shareplate.util.FileUtil;
import com.nd.qa.shareplate.util.FileZip;
import com.nd.qa.shareplate.util.FormatTimeUtil;
import com.nd.qa.shareplate.util.HttpPostUrl;
import com.nd.qa.shareplate.util.HttpUtil;
import com.nd.qa.shareplate.util.JsonUtil;


/**
 * <p>脚本项目控制类</p>
 * @author huangjian
 * @createDate 2015-09-08 下午 17:36:36
 * @version V1.0
 */
@Controller("com.nd.qa.shareplate.controller.ProjectController")
@RequestMapping("/project/*")
public class ProjectController {

    private static Logger log = LoggerFactory.getLogger(ProjectController.class);
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.LoginService")
    private LoginService loginService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ProjectService")
    private ProjectService projectService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ModuleService")
    private ModuleService moduleService;

    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.PageElementService")
    private PageElementService elementService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.PageService")
    private PageService pageService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ApkService")
    private ApkService apkService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ProjectTaskService")
    private ProjectTaskService operateProjectService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ProjectTypeService")
    private ProjectTypeService projectTypeService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ShareMessageService")
    private ShareMessageService sMessageService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ShareScriptService")
    private ShareScriptService scriptService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ShareSysLogService")
    private ShareSysLogService shareSysLogService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.TestApkService")
    private TestApkService testApkService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.PlatFormTypeService")
    private PlatFormTypeService platFormTypeService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ProjectTaskService")
    private ProjectTaskService projectTaskService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.TestCasesService")
    private TestCasesService testCasesService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.TestClassService")
    private TestClassService testClassService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.TestStepService")
    private TestStepService testStepService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ShareDeviceService")
    private ShareDeviceService deviceService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ProjectUserService")
    private ProjectUserService projectUserService;
    
    @Autowired
    @Qualifier("com.nd.qa.shareplate.service.ShareServerService")
    private ShareServerService shareServerService;
    
    @SuppressWarnings("unchecked")
    @RequestMapping("/totalProject")
    public String queryTotalProject(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        //获取session
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        if (sessionUserInfo==null) {
            return "/main/login";
        }
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        String projectName = request.getParameter("projectName");
        Project project = new Project();
        Integer totalPages = 0;//总记录数
        Integer currentPage = Integer.valueOf(String.valueOf(inParam.get("currentPage")));
        Integer pageSize = Integer.valueOf(String.valueOf(inParam.get("pageSize")));
        Integer startSize = (currentPage-1)*pageSize;
        project.setUserId(sessionUserInfo.getUserId());
        project.setProjectName(projectName);
        try {
            List<HashMap<String, Object>> totalProList = projectService.queryTotalProject(project);
            if (totalProList.size()>0&&totalProList.size()%pageSize==0) {
                totalPages = totalProList.size()/pageSize;
            }else {
                totalPages = totalProList.size()/pageSize + 1;
            }
            HashMap<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("startSize", startSize);
            paramMap.put("pageSize", pageSize);
            paramMap.put("projectName", projectName);
            paramMap.put("userId", sessionUserInfo.getUserId());
            List<HashMap<String, Object>> projectList = projectService.queryLimitProject(paramMap);
            model.addAttribute("projectList", projectList);
            model.addAttribute("totalPages", totalPages);   
        } catch (Exception e) {
            log.error("查询项目信息异常"+e);
            e.printStackTrace();
        }
        return "/main/projectdetail";
    }
    /**
     * 查询项目信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryTheProject")
    public void queryTheProject(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        //获取session
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        if (sessionUserInfo==null) {
            resultMap.put("code", "-1");
            resultMap.put("errorsList", "您还未登录");
        }
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        Integer projectId = Integer.valueOf((String) inParam.get("projectId"));
        Project project = new Project();
        project.setUserId(sessionUserInfo.getUserId());
        project.setProjectId(projectId);
        try {
            HashMap<String, Object> projectMap = projectService.queryTheProject(project);
            resultMap.put("projectMap", projectMap);
            resultMap.put("code", "0");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JsonUtil.toString(resultMap));
        }catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 返回新建项目界面
     * @return
     */
    @RequestMapping("/createProject")
    public String createProject(HttpServletRequest request,Model model){
        try {
            //查询头部菜单
            List<HashMap<String, Object>> menuList = loginService.queryHeaderMenuFunction();
            model.addAttribute("menuList", menuList);
            //查询项目类型
            List<HashMap<String,Object>> testList = projectService.queryTestType();
            List<HashMap<String,Object>> projectList = projectService.queryProjectType();
            //查询平台类型
            List<SharePlatFormType> sFormTypeList = platFormTypeService.queryPlatFormType();
            model.addAttribute("testList", testList);
            model.addAttribute("projectList", projectList);
            model.addAttribute("sFormTypeList", sFormTypeList);
        } catch (Exception e) {
            log.error("返回创建项目界面异常："+e);
            e.printStackTrace();
        }
        return "/main/newproject";
    }
    /**
     * 新项目插入数据
     * @param request
     * @param response
     * @param params
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/insertProject")
    public void insertProject(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        if (sessionUserInfo==null) {
            resultMap.put("code", "-1");
            resultMap.put("message", "您还未登录");
        }
        try {
            HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
            //查询项目序列号
            Integer projectId = projectService.queryProjectSeqByName("project_seq");
            Project project = new Project();
            project.setProjectId(projectId);
            project.setProjectMainActivity(String.valueOf(inParam.get("projectActivity")));
            project.setProjectDesc(String.valueOf(inParam.get("projectDesc")));
            String platformType = String.valueOf(inParam.get("platformType"));
            if ("1".equals(platformType)) {
            	 project.setProjectPackage("web");
			}else{
				project.setProjectPackage(String.valueOf(inParam.get("projectPackage")));
			}
            project.setProjectLoginUrl(String.valueOf(inParam.get("projectLoginUrl")));
            project.setProjectName(String.valueOf(inParam.get("projectTitle")));
            project.setTestType(String.valueOf(inParam.get("testType")));
            project.setPlatformType(Integer.valueOf(platformType));
            project.setProjectType(String.valueOf(inParam.get("projectType")));
            project.setProjectFlag(String.valueOf(inParam.get("projectFlag")));
            project.setUserId(sessionUserInfo.getUserId());
            project.setStatus("A");
            project.setProjectVersion("V1.0");
            project.setProjectExcuteStatus("1000");
            project.setProjectExcutedesc("项目创建成功");
            project.setCreateTime(FormatTimeUtil.dateToMapStr(new Date()));
            HashMap<String, Object> returnMap = projectService.insertProject(project);
            String code = (String) returnMap.get("code");
            if (CPResultCode.CP0000.equals(code)) {
                resultMap.put("code", "0");
                resultMap.put("message", "项目创建成功。");
            }else { 
                resultMap.put("code", "-2");
                resultMap.put("message", "项目创建失败。");
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JsonUtil.toString(resultMap));
        } catch(Exception e) {
            log.error("创建新项目异常："+e);
            e.printStackTrace();
        }
    }
    /**
     * 修改项目信息
     * @param session
     * @param request
     * @param response
     * @param params
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("saveProjectInfo")
    public void saveProjectInfo(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
        
        try {
            SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
            HashMap<String, Object> resultMap = new HashMap<String,Object>();
            if (sessionUserInfo==null) {
                resultMap.put("code", "-1");
                resultMap.put("message", "您还未登录");
                response.getWriter().print(JsonUtil.toString(resultMap));
            }
            HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
            Project project = new Project();
            project.setProjectMainActivity(String.valueOf(inParam.get("ciprojectActivity")));
            project.setProjectDesc(String.valueOf(inParam.get("ciprojectDesc")));
            project.setProjectPackage(String.valueOf(inParam.get("ciprojectPackage")));
            project.setTestType(String.valueOf(inParam.get("testType")));
            if ("1".equals(String.valueOf(inParam.get("platformType")))) {
            	project.setProjectPackage("web");
			}
            project.setProjectName(String.valueOf(inParam.get("ciprojectTitle")));
            project.setProjectType(String.valueOf(inParam.get("ciprojectType")));
            project.setProjectLoginUrl(String.valueOf(inParam.get("projectLoginUrl")));
            project.setPlatformType(Integer.valueOf(String.valueOf(inParam.get("platformType"))));
            project.setUserId(sessionUserInfo.getUserId());
            project.setProjectId(Integer.valueOf(String.valueOf(inParam.get("ciprojectId"))));
            project.setUpdateTime(FormatTimeUtil.dateToMapStr(new Date()));
            projectService.saveProjectInfo(project);
            resultMap.put("code", "0");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JsonUtil.toString(resultMap));
        } catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 删除项目
     * @param session
     * @param request
     * @param response
     * @param params
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("deleteProjectById")
    public void deleteProjectById(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
        
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        try {
            resultMap = projectService.deleteProjectById(Integer.valueOf(String.valueOf(inParam.get("projectId"))));
            String code = (String) resultMap.get("code");
            if (CPResultCode.CP0000.equals(code)) {
                resultMap.put("code", "0");
                resultMap.put("data", "删除成功");
            }else{
                resultMap.put("code", "-1");
                resultMap.put("data", "删除失败");
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JsonUtil.toString(resultMap));
        }catch (IOException e) {
            log.error(e.toString());
            e.printStackTrace();
        }catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 查询项目类型信息
     * @param request
     * @param response
     * @param params
     */
    @RequestMapping("/queryProjectType")
    public void queryProjectType(HttpServletRequest request,HttpServletResponse response,@RequestBody String params){
        
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        try {
            List<HashMap<String,Object>> typeList = projectService.queryProjectType();
            resultMap.put("typeList", typeList);
            resultMap.put("code", "0");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JsonUtil.toString(resultMap));
        }catch (IOException e) {
            log.error(e.toString());
            e.printStackTrace();
        }catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 返回脚本树首页
     * @param request  @RequestParam String projectid @RequestBody String params
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("showTreePage")
    public String showTreePage(HttpServletRequest request,HttpServletResponse response,HttpSession session, @RequestParam String projectid,Model model){
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        try {
            if (sessionUserInfo==null) {
                return "/main/login";
            }
            /*HashMap<String, Object> resultMap = new HashMap<String,Object>();
            HashMap<String, Object> paramMap = JsonUtil.toObject(params, HashMap.class);
            Integer projectid = Integer.valueOf(String.valueOf(paramMap.get("projectid")));*/
            model.addAttribute("projectid", projectid);
            //查询头部菜单
            List<HashMap<String, Object>> menuList = loginService.queryHeaderMenuFunction();
            //查询登录用户对该项目的权限
            HashMap<String,Object> inParam = new HashMap<String,Object>();
            inParam.put("projectId", Integer.valueOf(projectid));
            inParam.put("userId", sessionUserInfo.getUserId());
            HashMap<String, Object> projectMap= projectService.queryApplyProject(inParam);
            HashMap<String, Object> reMap = new HashMap<String,Object>();
            reMap.put("userName", sessionUserInfo.getUserName());
            reMap.put("userId", sessionUserInfo.getUserId());
            reMap.put("roleIds", sessionUserInfo.getRoleIds());
            reMap.put("projectRoleId", String.valueOf(projectMap.get("project_role_id")));
            reMap.put("projectType", String.valueOf(projectMap.get("project_type")));
            reMap.put("testType", String.valueOf(projectMap.get("test_type")));
            model.addAttribute("data", JsonUtil.toString(reMap));
            model.addAttribute("menuList", menuList);
            model.addAttribute("platformType", String.valueOf(projectMap.get("platform_type")));
            model.addAttribute("flag", "Y");
            model.addAttribute("testType", String.valueOf(projectMap.get("test_type")));
            /*resultMap.put("code", 0);
            resultMap.put("message", "成功");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JsonUtil.toString(resultMap));*/
        } catch (Exception e) {
            log.error("返回脚本树界面异常："+e);
            e.printStackTrace();
        }
        return "/main/projecttree";
    }
    /**
     * 构建脚本树
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/editTreeById")
    public void editTreeById(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        if (sessionUserInfo==null) {
            resultMap.put("code", "-2");
            resultMap.put("message", "您还未登录");
        }
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        Project project = new Project();
        Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectid")));
        project.setProjectId(projectId);
        project.setUserId(sessionUserInfo.getUserId());
        try {
            //查询该项目信息
            HashMap<String, Object> projectList = projectService.queryTheProject(project);
            //查询该项目下的所有模块
            Module module = new Module();
            module.setProjectId(projectId);
            List<HashMap<String, Object>> moduleList = moduleService.getProjectModule(module);
            resultMap.put("projectList", projectList);
            resultMap.put("moduleList", moduleList);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(JsonUtil.toString(resultMap));
        }catch (IOException e) {
            log.error("构建脚本树入参:"+e.toString());
            e.printStackTrace();
        }catch (Exception e) {
            log.error("构建脚本树数据:"+e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 下载项目脚本
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/downLoadScript")
    public void downLoadScript(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        if (sessionUserInfo==null) {
            resultMap.put("code", "-2");
            resultMap.put("message", "您还未登录");
        }
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        String projectId = String.valueOf(inParam.get("projectId"));
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            Project project = projectService.queryProjectById(Integer.valueOf(projectId));
            String projectUrl = project.getProjectUrl();
            //判断该文件路径是否可以访问
            URL url = new URL(projectUrl);
            HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
            int code = urlcon.getResponseCode();
            if (code==200) {
                resultMap.put("code", "0");
                resultMap.put("url", projectUrl);
            }else{
                resultMap.put("code", "-1");
                resultMap.put("message", "不存在项目脚本文件，请先生成脚本");
            }
            response.getWriter().print(JsonUtil.toString(resultMap));
        } catch (Exception e) {
            log.error("下载项目脚本:"+e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 生成脚本
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/buildScript")
    public void buildScript(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        
        try {
            HashMap<String, Object> resultMap = new HashMap<String,Object>();
            SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
            if (sessionUserInfo==null) {
                resultMap.put("code", "-2");
                resultMap.put("message", "请重新登录");
                response.getWriter().print(JsonUtil.toString(resultMap));
            }
            HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
            String projectId = String.valueOf(inParam.get("projectId"));
            String moduleId = String.valueOf(inParam.get("moduleId"));
            String scriptVersion = String.valueOf(inParam.get("scriptVersion"));
            //request.getServerName() request.getRemoteAddr()
            String headUrl = request.getScheme()+"://"+request.getServerName()+":"+ request.getLocalPort()+request.getContextPath();
            inParam.put("headUrl", headUrl);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            HashMap<String, Object> returnMap = createProjectScript(sessionUserInfo,response, request, inParam);
            if (CPResultCode.CP0000.equals(String.valueOf(returnMap.get("code")))) {
                String projectUrl = String.valueOf(returnMap.get("projectUrl"));
                String projectType = String.valueOf(returnMap.get("projectType"));
                projectUrl = headUrl+projectUrl;
                log.info("request.getScheme()="+request.getScheme()+",request.getRemoteAddr()="+request.getRemoteAddr()+","+InetAddress.getLocalHost().getHostAddress());
                //修改脚本项目的状态 
                Project project = new Project();
                project.setProjectId(Integer.valueOf(projectId));
                project.setProjectUrl(projectUrl);
                project.setProjectExcuteStatus("1002");
                project.setProjectExcutedesc("生成脚本成功");
                projectService.updateProject(project);
                //修改该项目类型脚本信息
                ProjectType pType = new ProjectType();
                pType.setShareProjectType(projectType);
                pType.setShareProjectUrl(projectUrl);
                projectTypeService.updateProjectType(pType);
                resultMap.put("code", "0");
            }else {
                resultMap.put("code", "-1");
                resultMap.put("message", returnMap.get("message"));
            }
            response.getWriter().print(JsonUtil.toString(resultMap));
        } catch (Exception e) {
            log.error("构建脚本树数据:"+e.toString());
            e.printStackTrace();
        }
    }

    public void test() throws Exception{
        List<PageElement> element = elementService.queryElementForPageId(16);
        System.out.println(element);
    }
    //----------------脚本生成----------------------

    FileUtil fileUtil = new FileUtil();
    public HashMap<String, Object> createProjectScript(SessionUserInfo sessionUserInfo,HttpServletResponse response,HttpServletRequest request,HashMap<String, Object> param){
        
        Integer projectId = Integer.valueOf(String.valueOf(param.get("projectId")));
        String moduleId = String.valueOf(param.get("moduleId"));
        String scriptName = String.valueOf(param.get("scriptName"));
        String scriptVersion = String.valueOf(param.get("scriptVersion"));
        String headUrl = String.valueOf(param.get("headUrl"));
        HashMap<String, Object> reMap = new HashMap<String,Object>();
        try {
            Project project = projectService.queryProjectById(projectId);
            //通过项目类型查询项目的配置信息
            ProjectType projectType = new ProjectType();
            projectType.setShareProjectType(project.getProjectType());
            List<ProjectType> pTypeList = projectTypeService.queryInfoByType(projectType);
            ProjectType pType = new ProjectType();
            //循环选择项目类型名称
            for (ProjectType projectType2 : pTypeList) {
                if (project.getProjectPackage().equals(projectType2.getPackageName())) {
                    pType = projectType2;
                }
            }
            Module module = new Module();
            module.setProjectId(projectId);
            if (moduleId!=null&&!"".equals(moduleId)) {
                module.setModuleId(Integer.valueOf(moduleId));
            }
            List<Module> modulesList = moduleService.queryModulesByProjectId(module);
            String projectDirPath = SysConstant.rootPath + sessionUserInfo.getUserId()+"/"+scriptName;
            fileUtil.deleteDir(new File(projectDirPath));
            fileUtil.createDir(projectDirPath);
            int flag = Integer.valueOf(project.getTestType()); 
            if (1==flag) {
                //创建测试项目的相关文件信息
                //new CreateRobotiumProject().createTestProject(SysConstant.rootPath,project.getProjectName(), project.getProjectPackage(), request);
                new CreateRobotiumTestDemo().createTestProject(SysConstant.rootPath+ sessionUserInfo.getUserId()+"/",scriptName, project.getProjectPackage(), request);
            }
            for (Module modules : modulesList) {
                //生成脚本
                createModelScript(modules,project,pType, projectDirPath+"/", flag);
                //testCreateScript(modelName, project, projectDirPath+"/", flag);
            }
            String zipPath = SysConstant.rootPath + sessionUserInfo.getUserId()+"/"+ scriptName+".zip";
            FileZip zc = new FileZip(zipPath);
            zc.compress(SysConstant.rootPath+ sessionUserInfo.getUserId()+"/", scriptName);
            //生成脚本至服务器地址
            String realPath = getFolder(request,sessionUserInfo.getUserId()+"/",SysConstant.scriptPath);
            File file=new File(zipPath);
            File saveFile=new File(new File(realPath),scriptName+".zip");
            /*if(!saveFile.getParentFile().exists()){
                saveFile.getParentFile().mkdirs();
            }*/
            String scriptNames = scriptName+".zip";
            String scriptUrl = SysConstant.scriptPath+sessionUserInfo.getUserId()+"/"+scriptNames;
            FileUtils.copyFile(file, saveFile);
            //生成测试apk
            //获取当前时间
            String currentTime = FormatTimeUtil.dateToMapStr(new Date());
            if (!"3".equals(project.getTestType())&&!"4".equals(project.getTestType())) {
                GenerateTestApk generateTestApk = new GenerateTestApk();
                generateTestApk.generateTestApk(SysConstant.rootPath +sessionUserInfo.getUserId()+"/"+ scriptName);
                File testApkFile = new File(SysConstant.rootPath+sessionUserInfo.getUserId()+"/" + scriptName+"/bin/test.apk");
                String realTestPath = getFolder(request,sessionUserInfo.getUserId()+"/",SysConstant.testPath);
                File saveTestFile=new File(new File(realTestPath),"test"+currentTime+".apk");
                FileUtils.copyFile(testApkFile, saveTestFile);
                //将测试apk脚本信息写入数据库
                ShareTestApk shareTestApk = new ShareTestApk();
                //查询是否已经存在对应的test-apk信息
                shareTestApk.setScriptName(scriptName);
                shareTestApk.setUserId(sessionUserInfo.getUserId());
                shareTestApk.setTestApkName("test"+currentTime+".apk");
                shareTestApk.setTestApkUrl(headUrl+SysConstant.testPath+sessionUserInfo.getUserId()+"/test"+currentTime+".apk");
                ShareTestApk testApk = testApkService.queryTestApkByName(shareTestApk);
                if (testApk==null) {
                    shareTestApk.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
                    shareTestApk.setStatus("A");
                    testApkService.insertTestInfo(shareTestApk);
                }else {
                    shareTestApk.setUpdateTime(FormatTimeUtil.dateToStrLong(new Date()));
                    testApkService.updateTestInfo(shareTestApk);
                }
            }
            //将脚本信息更新地址到项目类型表中
            ShareScript shareScript = new ShareScript();
            //判断是否已经存在该脚本信息
            shareScript.setScriptName(scriptNames);
            shareScript.setScriptVersion(scriptVersion);
            shareScript.setUserId(sessionUserInfo.getUserId());
            shareScript.setProjectId(projectId);
            if (modulesList.size()==1&&modulesList.get(0).getModuleOrder()!=null) {
            	shareScript.setClassName("MainActivityTest"+modulesList.get(0).getModuleOrder());
			}else{
				 shareScript.setClassName("MainActivityTest");
			}
            shareScript.setPlatformType(project.getPlatformType());
            List<ShareScript> scriptLists = scriptService.queryScripts(shareScript);
            if (scriptLists.size()==0) {
                shareScript.setScriptUrl(headUrl+scriptUrl);
                shareScript.setLocalScriptUrl(projectDirPath);
                shareScript.setProjectType(project.getProjectType());
                shareScript.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
                shareScript.setStatus("A");
                scriptService.insertSciptInfo(shareScript);
            }else {
                shareScript.setScriptId(scriptLists.get(0).getScriptId());
                shareScript.setUpdateTime(FormatTimeUtil.dateToStrLong(new Date()));
                scriptService.updateScriptInfo(shareScript);
            }
            reMap.put("code", CPResultCode.CP0000);
            reMap.put("projectUrl", scriptUrl);
            reMap.put("projectType", project.getProjectType());
        } catch (Exception e) {
            log.error("生成脚本异常："+e);
            e.printStackTrace();
            reMap.put("code", CPResultCode.CP1001);
            reMap.put("message", e.toString());
            return reMap;
        }
        return reMap;
    }
    /**
     * 根据传入的虚拟路径获取物理路径
     * @param path
     * @return
     */
    private String getPhysicalPath(HttpServletRequest request,String path,String realPath) {
        if (realPath == null || realPath.startsWith("/"))
            realPath = request.getSession().getServletContext()
                    .getRealPath(realPath);
        return realPath + "/" + path;
    }
    /**
     * 根据字符串创建本地目录 并建立子目录返回
     * @param path
     * @return
     */
    private String getFolder(HttpServletRequest request,String path,String realPath) {
        File dir = new File(this.getPhysicalPath(request, path ,realPath));
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return dir.getAbsolutePath();
    }

    /**
     * 生成一个模块的测试脚本
     * 
     * @param modelName
     * @throws Exception 
     */
    private boolean createModelScript(Module module,Project project,ProjectType pType, String projectDirPath, int flag) throws Exception {
        List<List<PageElement>> scriptList = new ArrayList<List<PageElement>>();
        scriptList = getModelScripts(module,project,pType, projectDirPath);
        if (scriptList == null) {
            return false;
        }
        if (flag == SysConstant.REALMONKEY) {
            RealMonkeyScriptTool pst = new RealMonkeyScriptTool(module,project, projectDirPath);
            pst.generateScript(scriptList);
        }else if (flag == SysConstant.ROBOTIUM) {
            RobotiumScriptTool jst = new RobotiumScriptTool(module,project,pType, projectDirPath);
            jst.generateScript(scriptList);
        }else if (flag == SysConstant.APPIUM) {
            AppiumScriptTool ast = new AppiumScriptTool(module, project, projectDirPath);
            ast.generateScript(scriptList);
        }else if (flag== SysConstant.MACACA) {
            MacacaScriptTool mst = new MacacaScriptTool(module,project,pType, projectDirPath);
            mst.generateScript(scriptList);
        }else if(flag== SysConstant.SELENIUM){
        	SeleniumScriptTool sst = new SeleniumScriptTool(module,project,pType, projectDirPath);
        	sst.generateScript(scriptList);
		}
        return true;
    }
    /*public boolean testCreateScript(Module module,Project project, String projectDirPath, int flag) throws Exception {
        //通过moduleId查询该模块下的最大层级
        int moduleId = module.getModuleId();
        int depth = pageService.queryMaxDepth(moduleId);
        if (depth==-1) {
            return false;
        }
        //查询该模块下层级为0的页面
        int count = 0;
        List<SharePage> pageList = pageService.queryPagesForDepth(moduleId,0);
        //查询层级为0 的页面是否存在子页面
        for (SharePage page : pageList) {
            if(!elementService.queryElementForPageId(page.getPageId()).isEmpty()){
                count++;
            }
        }
        if (count==0) {//说明只有apk启动后的首页
            return false;
        }
        //从最高层级开始查询元素的操作信息
        List<List<PageElement>> moduleScriptSet = new ArrayList<List<PageElement>>();
        for (int i = depth; i >=0; i--) {
            List<List<PageElement>> depthScriptSet = new ArrayList<List<PageElement>>();
            //查询每个层级的页面（从最高的层级开始）
            List<SharePage> endPages = pageService.queryPagesForDepth(moduleId, i);
            if (i == 0) {
                moduleScriptSet.addAll(getScriptList(endPages, moduleScriptSet)) ;
            }
            //遍历同一个层级下各个页面上的元素信息
            for (SharePage endPage : endPages) {
                List<PageElement> pageElements = elementService.queryElementForPageId(endPage.getPageId());
                //将查询出来的元素信息拷贝一份
                List<PageElement> endElementsCopy = deepCopy(pageElements);
                //删除重复的元素信息
                for (List<PageElement> pageElems : moduleScriptSet) {
                    for (PageElement pageElem : endElementsCopy) {
                        if (pageElems.contains(pageElem)) {
                            System.out.println("equal element");
                            pageElements.remove(pageElem);
                        }
                    }
                }
                //查询pageElements中是否存在子元素或者前置元素，以及该页面的父页面----直至根页面
                for (PageElement pageElement : pageElements) {
                    
                    List<PageElement> script = new ArrayList<PageElement>();
                    //根据该元素id是否是其他元素的前置元素来判断,一直找到没有子元素的元素（即最后操作的元素）
                    if (elementService.queryChildElementById(pageElement.getElementId()) != null) {
                        continue;
                    }
                    //从最后一个操作的元素开始反向查询上一次操作的元素 TODO
                    script.addAll(getAssociateElements(pageElement));
                    depthScriptSet.add(script);
                    System.out.println("depthScriptSet===="+depthScriptSet);
                }
            }
            moduleScriptSet.addAll(depthScriptSet);
            System.out.println("moduleScriptSet===="+moduleScriptSet);
        }
        if (flag == SysConstant.REALMONKEY) {
            RealMonkeyScriptTool pst = new RealMonkeyScriptTool(module,project, projectDirPath);
            pst.generateScript(moduleScriptSet);
        }else if (flag == SysConstant.ROBOTIUM) {
            RobotiumScriptTool jst = new RobotiumScriptTool(module,project,"", projectDirPath);
            jst.generateScript(moduleScriptSet);
        }else if (flag == SysConstant.APPIUM) {
            AppiumScriptTool ast = new AppiumScriptTool(module, project, projectDirPath);
            ast.generateScript(moduleScriptSet);
        }
        return true;
    }*/
    /**
     * 获取指定模块的所有脚本
     * 
     * @param modelName
     * @return
     * @throws Exception 
     */
    private List<List<PageElement>> getModelScripts(Module module,Project project,ProjectType pType,String projectDirPath) throws Exception {
        List<List<PageElement>> scriptList = new ArrayList<List<PageElement>>();
        int depth = pageService.queryMaxDepth(module.getModuleId());//获取脚本树最大的深度
        if (depth == -1) {
            return null;
        }
        int count = 0;
        //获取页面深度为0的元素信息
        List<SharePage> pages = pageService.queryPagesForDepth(module.getModuleId(), 0);
        for (SharePage page : pages) {
            List<PageElement> pageElements = elementService.queryElementForPageId(page.getPageId());//查询页面下的元素信息
            if(!pageElements.isEmpty()){
                count++;
            }
        }
        //判断是否创建了页面信息
        if (count==0) {
            return null;
        }
        // 获取模块所有根页面，从深度最高的开始遍历
        for (int i = depth; i >= 0; i--) {
            // Page rootPage = pages.get(0);
            List<List<PageElement>> lists = getScriptForDepth(scriptList, module.getModuleId(), i,module,project,pType, projectDirPath);
            //getScriptForDepth(scriptList, module.getModuleId(), i,module,project,pType, projectDirPath);
            scriptList.addAll(lists);
        }
        return scriptList;
    }

    
    /**
     * 获取指定深度回溯的脚本
     * 
     * @param programId--moduleId
     * @param depth
     * @param rootPageId
     * @return
     * @throws Exception 
     */
    private List<List<PageElement>> getScriptForDepth(
            final List<List<PageElement>> scriptLists, int moduleId, int depth,Module module,Project project,ProjectType pType,String projectDirPath) throws Exception {

        List<List<PageElement>> scriptList = new ArrayList<List<PageElement>>();
        //获取同一深度的页面信息
        List<SharePage> endPages = pageService.queryPagesForDepth(moduleId, depth);
        //深度为0，即为模块下的第一个节点
        if (depth == 0) {
            // 碎裂化脚本逻辑
            /*scriptList.addAll(getScriptList(endPages, scriptLists));
            RobotiumScriptTool jst = new RobotiumScriptTool(module,project,pType, projectDirPath);
            jst.generateScript(scriptList);*/ //碎裂化脚本逻辑
            return getScriptList(endPages, scriptLists);
        }

        // 回溯页面，组合脚本
        for (SharePage endPage : endPages) {

            List<PageElement> endElements = searchElements(scriptLists, endPage);

            for (PageElement element : endElements) {
                List<PageElement> script = new ArrayList<PageElement>();
                //传入前置元素id查询
                if (elementService.queryChildElementById(element.getElementId()) != null) {
                    continue;
                }
                //查询与其相关连的元素
                script.addAll(getAssociateElements(element));//element为存在前置级联关系元素的最后一个元素信息，获取该节点上一个操作的全部元素信息
                script.addAll(scriptPath(endPage));
                scriptList.add(script);
            }
            //  碎裂化脚本逻辑
            /*if (endElements.size()>0&&scriptList.size()>0) {
                RobotiumScriptTool jst = new RobotiumScriptTool(module,project,pType, projectDirPath);
                jst.generateScript(scriptList);
            }*/ // 碎裂化脚本逻辑
        }
        return scriptList;
    }

    /**
     * 查找根页面上的所有元素并去掉已经使用过的元素
     * @param scriptLists
     * @param endPage
     * @return
     * @throws Exception 
     */
    private List<PageElement> searchElements(final List<List<PageElement>> scriptLists,
            SharePage endPage) throws Exception {
        //获取页面元素信息
        List<PageElement> endElements = elementService.queryElementForPageId(endPage.getPageId());
        //拷贝元素信息
        List<PageElement> endElementsCopy = deepCopy(endElements);
        // 回溯操作路线   最大深度页面，第一次进来scriptLists为null
        for (List<PageElement> elems : scriptLists) {
            for (PageElement elem : endElementsCopy) {
                if (elems.contains(elem)) {
                    endElements.remove(elem);
                }
            }
        }
        return endElements;
    }

    /**
     * 获取根的脚本
     * @param endPages
     * @param scriptLists
     * @return
     * @throws Exception 
     */
    private List<List<PageElement>> getScriptList(List<SharePage> endPages,
            final List<List<PageElement>> scriptLists) throws Exception {
        List<List<PageElement>> scriptList = new ArrayList<List<PageElement>>();
        for (SharePage endPage : endPages) {
            List<PageElement> endElements = searchElements(scriptLists, endPage);
            for (PageElement element : endElements) {
                List<PageElement> script = new ArrayList<PageElement>();
                if (elementService.queryChildElementById(element.getElementId()) != null) {
                    continue;
                }
                script.addAll(getAssociateElements(element));
                scriptList.add(script);
            }
        }
        return scriptList;
    }

    /**
     * 获取能拼一个脚本的所有元素
     * 
     * @param endPage
     * @param rootPageId
     * @return
     * @throws Exception 
     */
    private List<PageElement> scriptPath(SharePage endPage) throws Exception {
        List<PageElement> script = new ArrayList<PageElement>();
//      ElementOperational elemOperate = iDataService.getElementOperational(endPage
//              .getPageId());
//      int pageId = iDataService.getPageForElement(elemOperate.getElementId());
        PageElement element = elementService.querySingleElementById(endPage.getElementTargetId());
        script.addAll(getAssociateElements(element));
        int pageId = element.getPageId();
        while (pageService.queryDepthForId(pageId) != 0) {
            SharePage page = pageService.queryPageById(pageId);
            element = elementService.querySingleElementById(page.getElementTargetId());
            pageId = element.getPageId();
            script.addAll(getAssociateElements(element));
        }
        return script;
    }
    
    private List<PageElement> getAssociateElements(PageElement element) throws Exception{
        List<PageElement> elements = new ArrayList<PageElement>();
        elements.addAll(getAllChildElements(element));
        if (Integer.valueOf(element.getElementPreciousId()) == 0) {
            return elements;
        }
        elements.addAll(getAllParentElements(element));
        return elements;
    }
    
    private List<PageElement> getAllChildElements(PageElement element) throws Exception{
        List<PageElement> elements = new ArrayList<PageElement>();
        List<PageElement> elementsTemp = new ArrayList<PageElement>();
        PageElement elementChild = elementService.queryChildElementById(element.getElementId());
        if (elementChild == null) {  
            elements.add(element);
            return elements;        
        }
        while(elementChild != null){
            elements.add(elementChild);
            elementChild = elementService.queryChildElementById(elementChild.getElementId());
        }
        System.out.println("elements.size()"+elements.size());
        for (int i = elements.size()-1; i >= 0; i--) {
            elementsTemp.add(elements.get(i));
        }
        return elementsTemp;
    }
    
    private List<PageElement> getAllParentElements(PageElement element) throws Exception{
        List<PageElement> elements = new ArrayList<PageElement>();
        PageElement parentElement = elementService.querySingleElementById(Integer.valueOf(element.getElementPreciousId()));
        if(parentElement!=null){
            elements.add(parentElement);
        	while(parentElement!=null&&parentElement.getElementPreciousId()!=0) {
                parentElement = elementService.querySingleElementById(Integer.valueOf(parentElement.getElementPreciousId()));
                if (parentElement!=null) {
                	elements.add(parentElement);
				}
			}
        }
        return elements;
    }
    /**
     * 深度复制
     * @param src
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<PageElement> deepCopy(List<PageElement> src) {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out;
        try {
            out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(
                    byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            List<PageElement> dest;
			dest = (List<PageElement>) in.readObject();
            return dest;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
        return null;
    }
    /**
     * 获取测试脚本,必须是生成完脚本且权限为3的项目才可以进行测试
     * @param request
     * @param response
     * @param session
     * @param params
     */
    @RequestMapping("/initTestScripts")
    public void initTestScripts(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
        	 HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        	String projectId = String.valueOf(inParam.get("projectId"));
            if (sessionUserInfo==null||"".equals(sessionUserInfo)) {
                resultMap.put("code", "-2");
                resultMap.put("message", "您还未登录");
                response.getWriter().print(JsonUtil.toString(resultMap));
            }
            ShareScript script = new ShareScript();
            script.setUserId(sessionUserInfo.getUserId());
            if (!"null".equals(projectId)&&projectId!=null&&!"".equals(projectId)) {
            	script.setProjectId(Integer.valueOf(projectId));
			}
            /*HashMap<String, Object> inParam = new HashMap<String,Object>();
            inParam.put("userId", sessionUserInfo.getUserId());
            inParam.put("ciProjectStatus", "1002");
            inParam.put("projectRoleId", "3");
            List<HashMap<String, Object>> scriptsList = projectService.queryScriptsById(inParam);*/
            List<ShareScript> scriptsList = scriptService.queryScripts(script);
            resultMap.put("scriptsList", scriptsList);
            response.getWriter().print(JsonUtil.toString(resultMap));
        } catch (IOException e) {
            log.error("查询脚本项目:"+e.toString());
            e.printStackTrace();
        }catch (Exception e) {
            log.error("查询脚本项目:"+e.toString());
            e.printStackTrace();
        }
    }
    /**
     * 发起测试任务请求
     * @param request
     * @param response
     * @param params
     */
    @SuppressWarnings({ "unchecked", "static-access" })
    @RequestMapping("/startToScriptTask")
    public void startToScriptTask(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
        
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        HashMap<String, Object> resultMap = new HashMap<String,Object>();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        String str = String.valueOf(inParam.get("scriptId"));
        String[] strings = str.split(",");
        Integer scriptId = Integer.valueOf(strings[0]);
        Integer projectId = Integer.valueOf(strings[1]);
        try {
            //查询脚本项目信息
            HashMap<String, Object> param = new HashMap<String,Object>();
            param.put("projectId", projectId);
            param.put("userId", sessionUserInfo.getUserId());
            HashMap<String, Object> projectMap = projectService.queryApplyProject(param);
            ShareScript script = new ShareScript();
            script.setScriptId(scriptId);
            script.setUserId(sessionUserInfo.getUserId());
            List<ShareScript> list = scriptService.queryScripts(script);
            ShareScript shareScript = list.get(0);
            String projectName = shareScript.getScriptName();
            String [] strings2 = projectName.split("\\.");
            projectName = strings2[0];
            String scriptUrl = shareScript.getScriptUrl();
            String scriptDentryID = shareScript.getDentryId();
            String testType = String.valueOf(projectMap.get("test_type"));
            String projectType = String.valueOf(projectMap.get("project_type"));
            String projectPackage = String.valueOf(projectMap.get("project_package"));
            String projectActivity = String.valueOf(projectMap.get("project_main_activity"));
            String platform_type = String.valueOf(projectMap.get("platform_type"));
            
            ProjectTaskTemp projectTaskTemp = new ProjectTaskTemp();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = simpleDateFormat.format(new Date());
            String serverIp = request.getServerName();
            projectTaskTemp.setUserId(sessionUserInfo.getUserId());
            projectTaskTemp.setApkLocalPath(shareScript.getLocalScriptUrl());
            projectTaskTemp.setProjectId(projectId);
            projectTaskTemp.setProjectName(projectName);
            projectTaskTemp.setProjectPackage(projectPackage);
            projectTaskTemp.setProjectActivity(projectActivity);
            projectTaskTemp.setTestType(testType);
            projectTaskTemp.setProjectType(projectType);
            projectTaskTemp.setScriptName(projectName+".zip");
            projectTaskTemp.setScriptUrl(scriptUrl);
            projectTaskTemp.setServerIp(serverIp);
            projectTaskTemp.setStatus("A");
            
            //apk和脚本上传cs，返回DentryID
            CSTools cs = new CSTools();
            String packageDentryID = "";
            String dentryId = "";
            String fileName = "";
            //查询apk信息
            System.out.println(String.valueOf(inParam.get("apkId")));
            if (String.valueOf(inParam.get("apkId"))!=null&&!"".equals(String.valueOf(inParam.get("apkId")))) {
            	Integer apkId = Integer.valueOf(String.valueOf(inParam.get("apkId")));
            	ApkInfo apk = new ApkInfo();
                apk.setApkId(apkId);
                List<ApkInfo> apkList = apkService.queryApkByUserId(apk);
                ApkInfo apkInfo = apkList.get(0);
                String apkPath = apkInfo.getApkPath();
                String localApkPath = apkInfo.getLocalApkPath();
                String apkName = apkInfo.getApkName();
                dentryId = apkInfo.getDentryId();
                
               //获取入参
                File file = new File(apkPath);
                String parentPath = file.getParent();    //源文件目录  
                fileName = file.getName();        //源文件名称  
                String prefixName = fileName.substring(0,fileName.lastIndexOf("."));
                
                projectTaskTemp.setApkPath(apkPath);
                if ("2".equals(platform_type)) {
                	projectTaskTemp.setApkName(prefixName+".apk");
    			}else if("3".equals(platform_type)){
    				projectTaskTemp.setApkName(prefixName+".ipa");
    			}
                try {
                	if ("2".equals(platform_type)) {
                        //Android
                		if (dentryId==null||"".equals(dentryId)) {
                            packageDentryID = cs.uploadPackage(apkName+".apk", localApkPath,"/Package/Andriod");
                		}else{
        					packageDentryID = apkInfo.getDentryId();
        				}
                		if(scriptDentryID==null||"".equals(scriptDentryID)){
                			scriptDentryID = cs.uploadScript(projectName+".zip", shareScript.getLocalScriptUrl()+".zip","/Script/Andriod");
                		}
                          
                    }
                    if ("3".equals(platform_type)) {
                        //ios
                    	if (dentryId==null||"".equals(dentryId)) {
                    		packageDentryID = cs.uploadPackage(apkName+".ipa", localApkPath,"/Package/ios");
                    	}else{
        					packageDentryID = apkInfo.getDentryId();
        				}
                    	if(scriptDentryID==null||"".equals(scriptDentryID)){
                    		scriptDentryID = cs.uploadScript(projectName+".zip", shareScript.getLocalScriptUrl()+".zip","/Script/ios");
                		}
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    //上传异常，设置状态 为0
                    apkService.updateAPKUploadStatus(apkId,0);
                    scriptService.updateScriptUploadStatus(shareScript.getScriptId(),0);
                    resultMap.put("code","-1");
                    resultMap.put("msg","资源上传异常，请重新上传...");
                    response.getWriter().print(JsonUtil.toString(resultMap));
                }
                //正常上传，修改dentryId，设置状态为1
                boolean dentryIdFlag = dentryId==null||"".equals(dentryId);
                boolean packageDentryFlag = packageDentryID!=null&&!"".equals(packageDentryID);
                if (dentryIdFlag&&packageDentryFlag) {
                	apkService.updateAPKInfo(apkId, packageDentryID);
                	apkService.updateAPKUploadStatus(apkId,1);
                }else{
                	 resultMap.put("code","-1");
                     resultMap.put("msg","项目：" +projectName+ "上传app资源文件失败...");
                     response.getWriter().print(JsonUtil.toString(resultMap));
                }
                scriptService.updateScriptInfo(shareScript.getScriptId(), scriptDentryID);
                scriptService.updateScriptUploadStatus(shareScript.getScriptId(),1);  
                if ("3".equals(testType)) {
                    projectTaskTemp.setTaskProgress(2);//脚本测试准备就绪状态
                }else {
                    projectTaskTemp.setTaskProgress(0);//脚本测试准备就绪状态
                }
                projectTaskTemp.setTaskProgressDesc("脚本项目准备就绪");
                projectTaskTemp.setPackageDentryId(packageDentryID);
    		}
            try {
            	//web端，脚本上传
                if ("1".equals(platform_type)) {
                    //Web
                	if(scriptDentryID==null||"".equals(scriptDentryID)){
            			scriptDentryID = cs.uploadScript(projectName+".zip", shareScript.getLocalScriptUrl()+".zip","/Script/Web");
            			//将上传返回的标识入库
            			scriptService.updateScriptInfo(shareScript.getScriptId(), scriptDentryID);
                        scriptService.updateScriptUploadStatus(shareScript.getScriptId(),1);
            		}
                }
			} catch (Exception e) {
				resultMap.put("code","-1");
                resultMap.put("msg","资源上传异常，请重新上传...");
                response.getWriter().print(JsonUtil.toString(resultMap));
			}
            projectTaskTemp.setScriptDentryId(scriptDentryID);
            operateProjectService.insertProjectInfo(projectTaskTemp);//添加任务队列         
            
            //加入自动化测试队列成功，更新数据
            Project project = new Project();
            project.setProjectExcuteStatus("1004");
            project.setProjectExcutedesc("测试项目加入队列成功");
            project.setProjectId(projectId);
            projectService.updateProject(project);
            
            //查询空闲的服务器
            ShareServer server = new ShareServer();
            server.setStatus("A");
            List<ShareServer> serverList = shareServerService.queryShareServer(server);
            //查询被测应用的登录信息
            List<ProjectUser> listUser = projectUserService.queryProjectUser(String.valueOf(projectId), platform_type);
             //检查设备信息
            String deviceId = "";
            String deviceVersion = "";
             if(!"1".equals(platform_type)){
            	 ShareDevice freeDevice = new ShareDevice();
                 freeDevice.setDeviceStatus("1");
                 freeDevice.setDeviceType(platform_type);//平台类型即为脚本执行的设备类型
                 ShareDevice device = deviceService.queryFreeDevices(freeDevice);//查询空闲设备
                 if (device!=null&&serverList.size()>0&&listUser.size()>0) {
                	 deviceId = device.getDeviceId();
                     deviceVersion = device.getDeviceVersion();
                 	ShareServer server2 = serverList.get(0);
                 	ProjectUser pUser = listUser.get(0);
                      //发起请求,1.获取脚本信息，修改脚本
                     HashMap<String, Object> paramMap = new HashMap<String, Object>();
                     paramMap.put("platformType", platform_type);
                     paramMap.put("apkUrl", packageDentryID);//packageDentryID
                     paramMap.put("platformVersion", deviceVersion);
                     paramMap.put("deviceId", deviceId);
                     paramMap.put("scriptUrl", scriptDentryID);//scriptDentryID
                     paramMap.put("projectId", String.valueOf(projectId));
                     paramMap.put("appName", fileName);
                     paramMap.put("projectPackage", projectPackage);
                     paramMap.put("projectActivity", projectActivity);
                     paramMap.put("host", server2.getServerIp());
                     paramMap.put("port", server2.getServerPort());
                     paramMap.put("serverId", String.valueOf(server2.getServerId()));
                     paramMap.put("projectUserId", String.valueOf(pUser.getProjectUserId()));
                     paramMap.put("userName", pUser.getLoginName());
                     paramMap.put("password", pUser.getLoginPwd());
                     paramMap.put("organizationId", pUser.getOrganizationId());
                     String url = "";
                     if ("3".equals(platform_type)) {
                         url = "http://172.18.162.225:8088/macaca/handleScript";//"http://172.18.162.225:9090/macaca/handleScript" http://192.168.239.106:8088/macaca/handleScript;
                     }else if ("2".equals(platform_type)) {
                         url = "http://192.168.239.106:9090/macaca/handleScript";
                     }
                     HttpPostUrl postUrl = new HttpPostUrl();
                     postUrl.sendPost(url, paramMap);
                    //修改服务器状态
                  	server2.setStatus("B");
                  	shareServerService.updateShareServer(server2);
                  	//修改设备状态
                  	ShareDevice shareDevice = new ShareDevice();
                  	shareDevice.setStatus("B");
                  	shareDevice.setDeviceId(dentryId);
                  	deviceService.updateDeviceStatus(shareDevice);
                  //修改登录账号状态
                    pUser.setStatus("B");
                    projectUserService.updateProjectUser(pUser);
                  }
             }else{
            	 if (listUser.size()>0) {
                  	ProjectUser pUser = listUser.get(0);
                       //发起请求,1.获取脚本信息，修改脚本
                      HashMap<String, Object> paramMap = new HashMap<String, Object>();
                      paramMap.put("platformType", platform_type);
                      paramMap.put("platformVersion", deviceVersion);
                      paramMap.put("scriptUrl", scriptDentryID);//scriptDentryID
                      paramMap.put("projectId", String.valueOf(projectId));
                      paramMap.put("appName", fileName);
                      paramMap.put("projectPackage", projectPackage);
                      paramMap.put("projectActivity", projectActivity);
                      paramMap.put("projectUserId", String.valueOf(pUser.getProjectUserId()));
                      paramMap.put("userName", pUser.getLoginName());
                      paramMap.put("password", pUser.getLoginPwd());
                      paramMap.put("organizationId", pUser.getOrganizationId());
                      String url = "http://192.168.239.136:8089/selenium/handleScript";;
                      HttpPostUrl postUrl = new HttpPostUrl();
                      postUrl.sendPost(url, paramMap);
                  	//修改登录账号状态
                    pUser.setStatus("B");
                    projectUserService.updateProjectUser(pUser);
                   }
             }
            resultMap.put("code","0");
            resultMap.put("msg","项目：" +projectName+ "加入测试队列成功，请等待测试结果...");
            response.getWriter().print(JsonUtil.toString(resultMap));
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code","-1");
            resultMap.put("msg","项目：加入测试队列异常...");
            try {
				response.getWriter().print(JsonUtil.toString(resultMap));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        }
    }
    /**
     * 发起测试请求
     * @param localApkPath
     * @param localScriptPath
     * @param deviceId
     */
    public void startToTask(String localApkPath,HashMap<String, Object> map){
        try {
            updateScript(localApkPath,map);
            //发起请求
            Integer resStatus = 200;
            if (resStatus==200) {
                //从任务列表中获取等待的任务信息
                ProjectTaskTemp projectTaskTemp = operateProjectService.getNextProjectInfo(SysConstant.PROCESS_STATUS_SYNC_END);
                HashMap<String, Object> pMap = new HashMap<String,Object>();
                pMap.put("scriptUrl", projectTaskTemp.getScriptLocalUrl());
                pMap.put("deviceId", projectTaskTemp.getDeviceName());
                updateScript(projectTaskTemp.getApkLocalPath(),pMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 修改脚本信息
     * @param shareScript
     * @param deviceId
     * @return
     */
    public void updateScript(String localApkPath,HashMap<String, Object> map){
        String localScriptPath = "";
        String deviceId = "";
        //解析脚本
        File file = new File(localScriptPath);
        BufferedReader bufferedReader = null;
        BufferedWriter bufWriter = null;
        try {
             bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            // 缓冲FileWriter
            String tmpLine = bufferedReader.readLine();
            while (tmpLine!=null) {
                if (tmpLine.contains("uDeviceName")) {
                    tmpLine.replace("uDeviceName", deviceId);
                }else if (tmpLine.contains("uDeviceId")) {
                    tmpLine.replace("uDeviceId", deviceId);
                }else if (tmpLine.contains("apkPath")) {
                    tmpLine.replace("apkPath", localApkPath);
                }
                tmpLine = bufferedReader.readLine();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedReader.close();
                bufWriter.flush();
                bufWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 
    }
    /**
     * 回调Jenkins执行结果
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
	@SuppressWarnings({ "unchecked", "static-access" })
	@RequestMapping("/getCallBack")
    public void getCallBack(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
    	
		HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
        try {
            Integer ciProjectId = Integer.valueOf(String.valueOf(param.get("projectId")));
            String  backDeviceId  = String.valueOf(param.get("deviceId"));
            String  serverId  = String.valueOf(param.get("serverId"));
        	String  deviceType  = String.valueOf(param.get("platformType"));
            boolean res = dealCallBack(param);
            //查询任务
            ProjectTaskTemp projectTaskTemp = projectTaskService.getNextProjectInfo(SysConstant.PROCESS_STATUS_TEST_START);
            if (projectTaskTemp!=null) {
                //分配任务
                //检查设备信息
                 ShareDevice freeDevice = new ShareDevice();
                 freeDevice.setDeviceStatus("1");
                 freeDevice.setDeviceType(deviceType);
                 ShareDevice device = deviceService.queryFreeDevices(freeDevice);
                 String deviceId = device.getDeviceId();
                 //查询空闲的服务器
                 ShareServer server = new ShareServer();
                 server.setStatus("A");
                 List<ShareServer> serverList = shareServerService.queryShareServer(server);
                 //查询被测应用的登录信息
                 List<ProjectUser> listUser = projectUserService.queryProjectUser(String.valueOf(ciProjectId), deviceType);
                 if (!CommonUtils.isEmpty(deviceId)&&serverList.size()>0) {
                	ShareServer server2 = serverList.get(0);
                	ProjectUser pUser = listUser.get(0);
                	//查询项目的信息
                	Project project =  projectService.queryProjectById(projectTaskTemp.getProjectId());
                	String platformType = String.valueOf(project.getPlatformType());
                     //发起请求,1.获取脚本信息，修改脚本
                    HashMap<String, Object> paramMap = new HashMap<String, Object>();
                    paramMap.put("apkUrl", projectTaskTemp.getApkPath());
                    paramMap.put("deviceId", deviceId);
                    paramMap.put("platformVersion", device.getDeviceVersion());
                    paramMap.put("scriptUrl", projectTaskTemp.getScriptUrl());
                    paramMap.put("projectId", projectTaskTemp.getProjectId());
                    paramMap.put("deviceType", deviceType);
                    
                    paramMap.put("platformType", platformType);
                    paramMap.put("apkUrl", projectTaskTemp.getPackageDentryId());//packageDentryID
                    paramMap.put("platformVersion", device.getDeviceVersion());
                    paramMap.put("deviceId", deviceId);
                    paramMap.put("scriptUrl", projectTaskTemp.getScriptDentryId());//scriptDentryID
                    paramMap.put("projectId", String.valueOf(projectTaskTemp.getProjectId()));
                    paramMap.put("appName", projectTaskTemp.getApkName());
                    paramMap.put("projectPackage", project.getProjectPackage());
                    paramMap.put("projectActivity", project.getProjectMainActivity());
                    paramMap.put("host", server2.getServerIp());
                    paramMap.put("port", server2.getServerPort());
                    paramMap.put("serverId", String.valueOf(server2.getServerId()));
                    paramMap.put("projectUserId", pUser.getProjectUserId());
                    paramMap.put("userName", pUser.getLoginName());
                    paramMap.put("password", pUser.getLoginPwd());
                    String url = "";
                    if ("3".equals(platformType)) {
                        url = "http://172.18.162.225:8088/macaca/handleScript";//"http://172.18.162.225:9090/macaca/handleScript" http://192.168.239.106:8088/macaca/handleScript;
                    }else if ("2".equals(platformType)) {
                        url = "http://192.168.239.106:9090/macaca/handleScript";
                    }else {
                        url = "http://192.168.239.106:9091/selenium/handleScript";
                    }
                    //String url = "http://192.168.239.106:9090/ssh_integrated_spring/handleScript";
                    new HttpPostUrl().sendPost(url, paramMap);
                 }
            }
        } catch (Exception e) {
            //将设备和服务器重置
        	dealCallBack(param);
            log.info("执行脚本回调异常getCallBack："+e);
        }
    }
	/**
	 * 处理结果
	 * @param param
	 * @return
	 */
    public boolean dealCallBack(HashMap<String, Object> param){
    	try {
    		Integer ciProjectId = Integer.valueOf(String.valueOf(param.get("projectId")));
            String  backDeviceId  = String.valueOf(param.get("deviceId"));
            String  deviceType  = String.valueOf(param.get("platformType"));
            String  serverId  = String.valueOf(param.get("serverId"));
            String  projectUserId  = String.valueOf(param.get("projectUserId"));
       	//将测试状态改为完成
           Project project = new Project();
          //project.setCiReportUrl(reportUrl);
           project.setProjectId(ciProjectId);
           project.setProjectExcuteStatus("1006");
           project.setProjectStatusDesc("测试完成");
           projectService.updateProject(project);
           //若存在未分配的任务则继续下发任务
           //关设备
           ShareDevice closeDevice = new ShareDevice();
           closeDevice.setDeviceId(backDeviceId);
           closeDevice.setDeviceStatus("1");
           closeDevice.setDeviceType(deviceType);
           deviceService.updateDeviceStatus(closeDevice);
           //打开服务
           ShareServer server = new ShareServer();
           server.setServerId(Integer.valueOf(serverId));
           server.setStatus("A");
           shareServerService.updateShareServer(server);
           //修改登录信息状态
           if (!"".equals(projectUserId)&&projectUserId!=null) {
        	   ProjectUser projectUser = new ProjectUser();
               projectUser.setProjectUserId(Integer.valueOf(projectUserId));
               projectUser.setStatus("A");
               projectUserService.updateProjectUser(projectUser);
           }
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
    	 return true;
    }
    /**
     * 测试报告首页
     * @param request
     * @param response
     * @param session
     * @param params
     * @return
     */
    @RequestMapping("/repindex")
    public String repindex(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
    	 SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        String projectId = String.valueOf(request.getParameter("projectId"));
        /*TestCases testCases = new TestCases();
        testCases.setClassId(tClass.getClassId());
        List<TestCases> tCases = testCasesService.queryTestCasesById(testCases);
        TestStep testStep = new TestStep();
        testStep.setCaseId(tCases.get(0).getCaseId());
        List<TestStep> list = testStepService.queryTestStepById(testStep);
        model.addAttribute("tClass", tClass);
        model.addAttribute("tCases", tCases);*/
        model.addAttribute("projectId", projectId);
        model.addAttribute("userName", sessionUserInfo.getUserName());
        return "/main/reportlist";
    }
    /**
     * 添加账号信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @return
     */
    @RequestMapping("/projectuser")
    public String projectuser(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
    	SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
    	String projectId = String.valueOf(request.getParameter("projectId"));
    	String platformType = String.valueOf(request.getParameter("platformType"));
    	//查询项目--登录信息
    	List<ProjectUser> list = projectUserService.queryProjectUser(projectId,platformType); 
    	model.addAttribute("list", list);
    	model.addAttribute("projectId", projectId);
    	model.addAttribute("userName", sessionUserInfo.getUserName());
    	return "/main/projectuser";
    }
    /**
     * 添加账号信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @return
     */
    @RequestMapping("/saveLoginInfo")
    public void saveLoginInfo(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
    	
    	SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
    	HashMap<String, Object> resultMap = new HashMap<String,Object>();
    	response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
    	HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
    	String projectId = String.valueOf(param.get("projectId"));
    	String projectName = String.valueOf(param.get("projectName"));
    	String platformType = String.valueOf(param.get("platformType"));
    	String organizationId = String.valueOf(param.get("organizationId"));
    	String loginName = String.valueOf(param.get("loginName"));
    	String loginPwd = String.valueOf(param.get("loginPwd"));
		try {
			//查询项目--登录信息
	    	ProjectUser projectUser = new ProjectUser();
	    	projectUser.setProjectId(projectId);
	    	projectUser.setPlatformType(platformType);
	    	projectUser.setOrganizationId(organizationId);
	    	projectUser.setLoginName(loginName);
	    	projectUser.setLoginPwd(loginPwd);
	    	projectUser.setCreateTime(FormatTimeUtil.dateToMapStr(new Date()));
	    	projectUser.setStatus("A");
	    	projectUserService.insertProjectUser(projectUser);
			resultMap.put("code","0");
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * 账号信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @return
     */
    @RequestMapping("/initUpdateInfo")
    public void initUpdateInfo(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
    	
    	HashMap<String, Object> resultMap = new HashMap<String,Object>();
    	response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
    	HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
    	String projectId = String.valueOf(param.get("projectId"));
    	String platformType = String.valueOf(param.get("platformType"));
		try {
	    	ProjectUser projectUser = new ProjectUser();
	    	projectUser.setProjectId(projectId);
	    	projectUser.setPlatformType(platformType);
	    	projectUser.setStatus("A");
	    	List<ProjectUser> list = projectUserService.queryProjectUser(projectId, platformType);
			resultMap.put("code","0");
			resultMap.put("list",list);
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * 修改账号信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @return
     */
    @RequestMapping("/updateLoginInfo")
    public void updateLoginInfo(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
    	
    	HashMap<String, Object> resultMap = new HashMap<String,Object>();
    	response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
    	HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
    	String projectUserId = String.valueOf(param.get("projectUserId"));
    	String organizationId = String.valueOf(param.get("organizationId"));
    	String loginName = String.valueOf(param.get("loginName"));
    	String loginPwd = String.valueOf(param.get("loginPwd"));
		try {
			//查询项目--登录信息
	    	ProjectUser projectUser = new ProjectUser();
	    	projectUser.setProjectUserId(Integer.valueOf(projectUserId));
	    	projectUser.setOrganizationId(organizationId);
	    	projectUser.setLoginName(loginName);
	    	projectUser.setLoginPwd(loginPwd);
	    	projectUserService.updateProjectUser(projectUser);
			resultMap.put("code","0");
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * 获取测试报告信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     * @return
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("/getReporter")
    public void getReporter(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        
        try {
        	HashMap<String, Object> resultMap = new HashMap<String,Object>();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
        	Integer projectId = Integer.valueOf(String.valueOf(param.get("projectId")));
            //查询Class
            TestClass testClass = new TestClass();
            testClass.setProjectId(projectId);
            List<TestClass> tClasses = testClassService.queryTestClassById(testClass);
            //查询项目信息
            try {
				Project project = projectService.queryProjectById(projectId);
				resultMap.put("project", project);
				//查询设备信息
			} catch (Exception e) {
				e.printStackTrace();
			}
            /*TestCases testCases = new TestCases();
            testCases.setClassId(tClass.getClassId());
            List<TestCases> tCases = testCasesService.queryTestCasesById(testCases);
            TestStep testStep = new TestStep();
            testStep.setCaseId(tCases.get(0).getCaseId());
            List<TestStep> list = testStepService.queryTestStepById(testStep);
            model.addAttribute("tClass", tClass);
            model.addAttribute("tCases", tCases);*/
            resultMap.put("code","0");
            resultMap.put("tClasses",tClasses);
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    /**
     * 报告详情
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
    @SuppressWarnings("unchecked")
	@RequestMapping("/reportDetail")
    public void reportDetail(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        
        try {
        	HashMap<String, Object> resultMap = new HashMap<String,Object>();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
        	Integer projectId = Integer.valueOf(String.valueOf(param.get("projectId")));
        	Integer classId = Integer.valueOf(String.valueOf(param.get("classId")));
            //查询Class
            TestClass testClass = new TestClass();
            testClass.setProjectId(projectId);
            testClass.setClassId(classId);
            List<TestClass> tClasses = testClassService.queryTestClassById(testClass);
            TestCases testCases = new TestCases();
            testCases.setClassId(classId);
            List<TestCases> tCases = testCasesService.queryTestCasesById(testCases);
            //查询设备信息
            ShareDevice shareDevice = new ShareDevice();
            shareDevice.setDeviceId(tClasses.get(0).getDeviceId());
            ShareDevice device = deviceService.queryFreeDevices(shareDevice);
            resultMap.put("code","0");
            //resultMap.put("tClasses",tClasses);
            resultMap.put("tCases",tCases);
            resultMap.put("device",device);
			response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    /**
     * 测试报告回归
     * @param request
     * @param response
     * @param session
     * @param params
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/pushReport")
    public void pushReport(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
        HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
        Integer ciProjectId = Integer.valueOf(String.valueOf(param.get("ciProjectId")));
        String  ciReportUrl  = String.valueOf(param.get("reportUrl"));
        String  reportName  = String.valueOf(param.get("reportName"));
        String  userId  = String.valueOf(param.get("userId"));
        try {
            //将测试报告下载一份到cidemo上
            String realPath = getFolder(request,userId+"/",SysConstant.reportPath);
            HttpUtil.downloadFile(realPath+"/"+reportName, ciReportUrl);
            //修改项目记录信息
            String reportUrl = request.getScheme()+"://"+request.getRemoteAddr()+":"+ request.getLocalPort()+request.getContextPath()+SysConstant.reportPath+userId+"/"+reportName;
            URLDecoder.decode(reportUrl,"UTF-8");
            Project project = new Project();
            //project.setCiReportUrl(reportUrl);
            project.setProjectId(ciProjectId);
            project.setProjectStatus("1006");
            project.setProjectStatusDesc("测试完成");
            projectService.updateProject(project);
             JSONObject json = new JSONObject();
             json.put("code", "0");
             json.put("msg", "项目：测试成功");
             response.setContentType("application/json;charset=UTF-8");
             response.getWriter().print(json);
             response.getWriter().flush();
             response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 遍历apk请求
     * @param request
     * @param response
     * @param session
     * @param params
     */
    @RequestMapping("/traversalApk")
    public void traversalApk(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
        String xmlPath = "E:\\baiduyun\\input.txt";
        try {
            File inputFile = new File(xmlPath);
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputFile);
            System.out.println("Root element :" 
                    + document.getRootElement().getName());
            Element classElement = document.getRootElement();
            List<Node> nodes = classElement.selectNodes("/class/student");
            for (Node node : nodes) {
                System.out.println("\nCurrent Element :" 
                           + node.getName());
                System.out.println("Student roll no : " 
                           + node.valueOf("rollno") );
                System.out.println("First Name : " + node.selectSingleNode("firstname").getText());
                System.out.println("Last Name : " + node.selectSingleNode("lastname").getText());
                System.out.println("First Name : " + node.selectSingleNode("nickname").getText());
                System.out.println("Marks : " + node.selectSingleNode("marks").getText());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        
    }
    /**
     * 
     * @param request
     * @param response
     * @param session
     * @param params
     */
    @RequestMapping("/queryInfoByType")
    public void queryInfoByType(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
         ProjectType type = new ProjectType();
         type.setShareProjectType(params);
         List<ProjectType> pType = projectTypeService.queryInfoByType(type);
         JSONObject json = new JSONObject();
         json.put("code", "0");
         json.put("pType", pType);
         response.setContentType("application/json;charset=UTF-8");
         try {
             response.getWriter().print(json);
             response.getWriter().flush();
             response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 
     * @param request
     * @param response
     * @param session
     * @param params
     * @return
     */
    @RequestMapping("/queryProjectSeqByName")
    public void queryProjectSeqByName(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
         Integer projectId = projectService.queryProjectSeqByName(params);
         JSONObject json = new JSONObject();
         json.put("code", "0");
         json.put("projectId", projectId);
         response.setContentType("application/json;charset=UTF-8");
         try {
             response.getWriter().print(json);
             response.getWriter().flush();
             response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 
     * @param request
     * @param response
     * @param session
     * @param params
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/insertProjectInfo")
    public void insertProjectInfo(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
         
        HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
        String userId = String.valueOf(param.get("userId"));
        String apkPath = String.valueOf(param.get("apkPath"));
        String apkName = String.valueOf(param.get("apkName"));
        String scriptName = String.valueOf(param.get("scriptName"));
        String scriptUrl = String.valueOf(param.get("scriptUrl"));
        String projectId = String.valueOf(param.get("projectId"));
        String projectName = String.valueOf(param.get("projectName"));
        String packageName = String.valueOf(param.get("packageName"));
        String mainActivity = String.valueOf(param.get("mainActivity"));
        String projectType = String.valueOf(param.get("projectType"));
        String taskProgress = String.valueOf(param.get("taskProgress"));
        String taskStatus = String.valueOf(param.get("taskStatus"));
        String tasdStatusDesc = String.valueOf(param.get("tasdStatusDesc"));
        
        ProjectTaskTemp projectTaskTemp = new ProjectTaskTemp();
        projectTaskTemp.setUserId(userId);
        projectTaskTemp.setApkPath(apkPath);
        projectTaskTemp.setApkName(apkName);
        projectTaskTemp.setProjectId(Integer.valueOf(projectId));
        projectTaskTemp.setProjectName(projectName);
        projectTaskTemp.setProjectPackage(packageName);
        projectTaskTemp.setProjectActivity(mainActivity);
        projectTaskTemp.setTestType("1");
        projectTaskTemp.setProjectType(projectType);
        projectTaskTemp.setScriptName(scriptName);
        projectTaskTemp.setScriptUrl(scriptUrl);
        projectTaskTemp.setStatus("A");
        projectTaskTemp.setTaskProgress(0);//脚本测试准备就绪状态
        projectTaskTemp.setTaskProgressDesc("脚本项目准备就绪");
        operateProjectService.insertProjectInfo(projectTaskTemp); 
         JSONObject json = new JSONObject();
         json.put("code", "0");
         json.put("msg", "项目：测试成功");
         response.setContentType("application/json;charset=UTF-8");
         try {
             response.getWriter().print(json);
             response.getWriter().flush();
             response.getWriter().close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 录入99u数据
     * @param request
     * @param response
     * @param session
     * @param params
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/insertMessage")
    public void insertMessage(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
        HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
        String jobId = String.valueOf(param.get("jobId"));
        String jobName = String.valueOf(param.get("jobName"));
        String groupId = String.valueOf(param.get("groupId"));
        String buildTime = String.valueOf(param.get("buildTime"));
        String buildStatus = String.valueOf(param.get("buildStatus"));
        String downloadUrl = String.valueOf(param.get("downloadUrl"));
        String codeUrl = String.valueOf(param.get("codeUrl"));
        String factoryType = String.valueOf(param.get("factoryType"));
        ShareMessage sMessage = new ShareMessage();
        sMessage.setJobId(jobId);
        sMessage.setJobName(jobName);
        sMessage.setGroupId(groupId);
        sMessage.setBuildTime(buildTime);
        sMessage.setBuildStatus(buildStatus);
        sMessage.setDownloadUrl(downloadUrl);
        sMessage.setCodeUrl(codeUrl);
        sMessage.setFactoryType(factoryType);
        sMessage.setStatus("A");
        try {
            sMessageService.insertMessage(sMessage);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
         JSONObject json = new JSONObject();
         json.put("code", "0");
         json.put("msg", "录入数据成功");
         response.setContentType("application/json;charset=UTF-8");
         try {
             response.getWriter().print(json);
             response.getWriter().flush();
             response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 查询99u推送的消息
     * @param request
     * @param response
     * @param session
     * @param params
     */
    @RequestMapping("/queryMsgInfo")
    public void queryMsgInfo(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
        ShareMessage sMessage = new ShareMessage();
        sMessage.setJobId(params);
        try {
            ShareMessage message = sMessageService.queryMsgInfo(sMessage);
            JSONObject json = new JSONObject();
            if (message==null) {
                json.put("code", "-1");
            }else {
                json.put("code", "0");
            }
            json.put("msg", message);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
    }
    
    
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryModels")
    public void queryModels(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params){
        
        HashMap<String, Object> param = JsonUtil.toObject(params, HashMap.class);
        String projectId = String.valueOf(param.get("projectId"));
        Module module = new Module();
        try {
            module.setProjectId(Integer.valueOf(projectId));
            List<Module> modulesList = moduleService.queryModulesByProjectId(module);
            JSONObject json = new JSONObject();
            if (modulesList==null) {
                json.put("code", "-1");
            }else {
                json.put("code", "0");
            }
            json.put("modulesList", modulesList);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
    }
    /**
     * 
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/totalScript")
    public String totalScript(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        //获取session
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        if (sessionUserInfo==null) {
            return "/main/login";
        }
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        ShareScript shareScript = new ShareScript();
        Integer totalPages = 0;//总记录数
        Integer currentPage = Integer.valueOf(String.valueOf(inParam.get("currentPage")));
        Integer pageSize = Integer.valueOf(String.valueOf(inParam.get("pageSize")));
        Integer startSize = (currentPage-1)*pageSize;
        shareScript.setUserId(sessionUserInfo.getUserId());
        try {
            List<ShareScript> totalList = scriptService.queryScripts(shareScript);
            if (totalList.size()>0&&totalList.size()%pageSize==0) {
                totalPages = totalList.size()/pageSize;
            }else {
                totalPages = totalList.size()/pageSize + 1;
            }
            HashMap<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("startSize", startSize);
            paramMap.put("pageSize", pageSize);
            paramMap.put("userId", sessionUserInfo.getUserId());
            List<ShareScript> scriptList = scriptService.queryLimitScript(paramMap);
            model.addAttribute("scriptList", scriptList);
            model.addAttribute("totalPages", totalPages);   
        } catch (Exception e) {
            log.error("查询脚本信息异常"+e);
            e.printStackTrace();
        }
        return "/main/scriptdetail";
    }
    
    
    /**
     * 查询项目中最新的脚本
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/queryLatestScriptByUserId")
    public void queryLatestScriptByUserId(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        String userId = String.valueOf(inParam.get("userId"));
        String projectType = String.valueOf(inParam.get("projectType"));
        ShareScript shareScript = new ShareScript();
        shareScript.setUserId(userId);
        shareScript.setProjectType(projectType);
        try {
            List<ShareScript> scriptsList = scriptService.queryLatestScriptByUserId(shareScript);
            JSONObject json = new JSONObject();
            if (scriptsList.size()>0) {
                json.put("script", scriptsList.get(0));
            }
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            response.getWriter().flush();
            response.getWriter().close();   
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除脚本信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/delScript")
    public void delScript(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        String scriptId = String.valueOf(inParam.get("scriptId"));
        ShareScript shareScript = new ShareScript();
        shareScript.setScriptId(Integer.valueOf(scriptId));
        try {
             scriptService.delScript(shareScript);
            JSONObject json = new JSONObject();
            json.put("code", "0");
            json.put("msg", "删除脚本成功");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            response.getWriter().flush();
            response.getWriter().close();   
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 删除脚本信息
     * @param request
     * @param response
     * @param session
     * @param params
     * @param model
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/addLog")
    public void addLog(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        String logMsg = String.valueOf(inParam.get("logMsg"));
        String beginTime = String.valueOf(inParam.get("beginTime"));
        ShareSysLog shareSysLog = new ShareSysLog();
        shareSysLog.setLogMsg(logMsg);
        shareSysLog.setBeginTime(beginTime);
        shareSysLog.setStatus("A");
        try {
            shareSysLogService.addLog(shareSysLog);
            JSONObject json = new JSONObject();
            json.put("code", "0");
            json.put("msg", "添加日志成功");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            response.getWriter().flush();
            response.getWriter().close();   
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/webProject")
    public String webProject(HttpServletRequest request,HttpServletResponse response,HttpSession session,@RequestBody String params,Model model){
        //获取session
        SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
        if (sessionUserInfo==null) {
            return "/main/login";
        }
        HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
        String projectName = request.getParameter("projectName");
        Project project = new Project();
        Integer totalPages = 0;//总记录数
        Integer currentPage = Integer.valueOf(String.valueOf(inParam.get("currentPage")));
        Integer pageSize = Integer.valueOf(String.valueOf(inParam.get("pageSize")));
        Integer startSize = (currentPage-1)*pageSize;
        project.setUserId(sessionUserInfo.getUserId());
        project.setProjectName(projectName);
        project.setPlatformType(1);
        try {
            List<HashMap<String, Object>> totalProList = projectService.queryTotalProject(project);
            if (totalProList.size()>0&&totalProList.size()%pageSize==0) {
                totalPages = totalProList.size()/pageSize;
            }else {
                totalPages = totalProList.size()/pageSize + 1;
            }
            HashMap<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("startSize", startSize);
            paramMap.put("pageSize", pageSize);
            paramMap.put("projectName", projectName);
            paramMap.put("userId", sessionUserInfo.getUserId());
            paramMap.put("platformType", 1);
            List<HashMap<String, Object>> projectList = projectService.queryLimitProject(paramMap);
            model.addAttribute("projectList", projectList);
            model.addAttribute("totalPages", totalPages);   
        } catch (Exception e) {
            log.error("查询项目信息异常"+e);
            e.printStackTrace();
        }
        return "/main/webproject";
    }
}
